<?php

class Grid extends AppBaseController 
{
	private $obj;
	private $db;
	private $where;
	public $select;
	public $primary;
	public $table;
	public $fields;
	public $status;
	public $paginacao;
	public $pagina;
	
	public function __construct($class)
	{
		$this->table = $class;
		
		$this->obj = new $class;
		
		$this->fields  = $this->obj->getFields();
		$this->primary = $this->obj->getPrimary();
		$this->db      = $this->obj->getAdapter();
		
		array_unshift($this->fields, $this->primary);
		
		$this->view();		
	}
	
	public function select()
	{
		$this->select = $this->db->select()->from($this->table, $this->fields);
	}
	
	public function view()
	{
		if(method_exists($this->obj, "getView"))
		{
			$this->table = $this->obj->getView();
		}
		
		if(method_exists($this->obj, "getStatus"))
		{
			$this->status = $this->obj->getStatus();
		}
	}
	
	public function run()
	{
		
		/**
		 * Total de resgistros.
		 */
		if($_POST["busca"][0])
		{
			$sql   = $this->select->__toString();
			$array = $this->db->fetchAll($sql);
			
			$numRows = sizeof($array);
		}
		else
		{
			$query   = $this->db->select()->from($this->table, 'count(*)');
			$numRows = $this->db->fetchOne($query);				
		}		
		
		$this->paginacao($numRows);
		$sql   = $this->select->__toString();
		//echo $sql;
		$array = $this->db->fetchAll($sql);
		
		return $array;
	}
	
	public function paginacao($num)
	{
		$this->paginacao = new Paginacao($num);
		
		$pagina = $_GET["pagina"];		
		
		$pagina = (!$pagina)?1:$pagina;
		
		$this->paginacao->setTotalRegistrosPagina($this->limit)
			->setPaginaAtual($pagina)
			->paginar();
		
		if($pagina == "*")
		{
			return;
		}
		
		$this->select->limitPage($pagina, $this->limit);
	}
}

?>
